<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="活动名称" prop="activityName">
        <el-input
          v-model="queryParams.activityName"
          placeholder="请输入活动名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动开始时间" prop="activityStartTime">
        <el-date-picker clearable
          v-model="queryParams.activityStartTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择活动开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="活动结束时间" prop="activityEndTime">
        <el-date-picker clearable
          v-model="queryParams.activityEndTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择活动结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="成团所需人数" prop="requiredGroupSize">
        <el-input
          v-model="queryParams.requiredGroupSize"
          placeholder="请输入成团所需人数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动类型" prop="activityCategoryId">
        <el-select v-model="queryParams.activityCategoryId" placeholder="请选择活动类型" clearable style="width: 180px">
          <el-option
            v-for="item in activityTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="活动状态" prop="activityStatus">
        <el-select v-model="queryParams.activityStatus" placeholder="请选择活动状态" clearable style="width: 150px">
          <el-option label="未开始" :value="0" />
          <el-option label="进行中" :value="1" />
          <el-option label="已停用" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable style="width: 150px">
          <el-option label="未提交" :value="0" />
          <el-option label="待审核" :value="1" />
          <el-option label="通过" :value="2" />
          <el-option label="驳回" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="拼团有效时长" prop="groupExpireHour">
        <el-input
          v-model="queryParams.groupExpireHour"
          placeholder="请输入拼团有效时长"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['group:check_active:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['group:check_active:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['group:check_active:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['group:check_active:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="check_activeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="活动ID" align="center" prop="id" />
      <el-table-column label="活动名称" align="center" prop="activityName" />
      <el-table-column label="活动描述" align="center" prop="activityDescription" />
      <el-table-column label="活动类型" align="center" prop="activityCategoryId">
        <template slot-scope="scope">
          <span>{{ getActivityTypeName(scope.row.activityCategoryId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动开始时间" align="center" prop="activityStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.activityStartTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动结束时间" align="center" prop="activityEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.activityEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="成团所需人数" align="center" prop="requiredGroupSize" />
      <el-table-column label="活动状态" align="center" prop="activityStatus">
        <template slot-scope="scope">
          <el-tag :type="getActivityStatusType(scope.row.activityStatus)">
            {{ getActivityStatusText(scope.row.activityStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="auditStatus">
        <template slot-scope="scope">
          <el-tag :type="getAuditStatusType(scope.row.auditStatus)">
            {{ getAuditStatusText(scope.row.auditStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="拼团有效时长" align="center" prop="groupExpireHour" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <!-- 平台审核操作按钮 -->
          <el-button
            v-if="scope.row.auditStatus === 1"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleAuditApprove(scope.row)"
            style="color: #67C23A;"
          >审核通过</el-button>
          
          <el-button
            v-if="scope.row.auditStatus === 1"
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="handleAuditReject(scope.row)"
            style="color: #F56C6C;"
          >审核驳回</el-button>
          
          <!-- 通用管理操作按钮 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['group:check_active:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['group:check_active:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :layout="'total, sizes, prev, pager, next, jumper'"
      @pagination="getList"
    />

    <!-- 添加或修改平台审核拼团活动对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="form.activityName" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动描述" prop="activityDescription">
          <el-input v-model="form.activityDescription" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="活动类型" prop="activityCategoryId">
          <el-select v-model="form.activityCategoryId" placeholder="请选择活动类型" clearable style="width: 100%">
            <el-option
              v-for="item in activityTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动开始时间" prop="activityStartTime">
          <el-date-picker clearable
            v-model="form.activityStartTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择活动开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动结束时间" prop="activityEndTime">
          <el-date-picker clearable
            v-model="form.activityEndTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择活动结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="成团所需人数" prop="requiredGroupSize">
          <el-input v-model="form.requiredGroupSize" placeholder="请输入成团所需人数" />
        </el-form-item>
        <el-form-item label="拼团有效时长" prop="groupExpireHour">
          <el-input v-model="form.groupExpireHour" placeholder="请输入拼团有效时长" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCheck_active, getCheck_active, delCheck_active, addCheck_active, updateCheck_active, getActivityTypes, auditActivity } from "@/api/group/check_active"

export default {
  name: "Check_active",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 活动类型选项
      activityTypeOptions: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 平台审核拼团活动表格数据
      check_activeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        activityName: null,
        activityDescription: null,
        activityCategoryId: null,
        activityStartTime: null,
        activityEndTime: null,
        requiredGroupSize: null,
        activityStatus: null,
        auditStatus: null,
        groupExpireHour: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        activityName: [
          { required: true, message: "活动名称不能为空", trigger: "blur" }
        ],
        activityCategoryId: [
          { required: true, message: "关联活动分类ID不能为空", trigger: "change" }
        ],
        activityStartTime: [
          { required: true, message: "活动开始时间不能为空", trigger: "blur" }
        ],
        activityEndTime: [
          { required: true, message: "活动结束时间不能为空", trigger: "blur" }
        ],
        requiredGroupSize: [
          { required: true, message: "成团所需人数不能为空", trigger: "blur" }
        ],


      }
    }
  },
  created() {
    this.getList()
    this.getActivityTypes()
  },
  methods: {
    /** 查询平台审核拼团活动列表 */
    getList() {
      this.loading = true
      listCheck_active(this.queryParams).then(response => {
        this.check_activeList = response.data.rows
        this.total = response.data.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        activityName: null,
        activityDescription: null,
        activityCategoryId: null,
        activityStartTime: null,
        activityEndTime: null,
        requiredGroupSize: null,
        activityStatus: null,
        auditStatus: null,
        groupExpireHour: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams.pageNum = 1
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加平台审核拼团活动"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getCheck_active(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改平台审核拼团活动"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保数字字段的数据类型正确
          const formData = {
            ...this.form,
            activityCategoryId: this.form.activityCategoryId ? Number(this.form.activityCategoryId) : null,
            requiredGroupSize: this.form.requiredGroupSize ? Number(this.form.requiredGroupSize) : null,
            groupExpireHour: this.form.groupExpireHour ? Number(this.form.groupExpireHour) : null
          }
          
          // 新增时不发送活动状态和审核状态，由后端设置默认值
          if (this.form.id == null) {
            // 新增时删除这两个字段
            delete formData.activityStatus
            delete formData.auditStatus
            
            addCheck_active(formData).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          } else {
            // 修改时保留状态字段
            formData.activityStatus = this.form.activityStatus !== null ? Number(this.form.activityStatus) : null
            formData.auditStatus = this.form.auditStatus !== null ? Number(this.form.auditStatus) : null
            
            updateCheck_active(formData).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除平台审核拼团活动编号为"' + ids + '"的数据项？').then(function() {
        return delCheck_active(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('group/check_active/export', {
        ...this.queryParams
      }, `check_active_${new Date().getTime()}.xlsx`)
    },
    /** 获取活动类型列表 */
    getActivityTypes() {
      getActivityTypes().then(response => {
        if (response.code === 200) {
          this.activityTypeOptions = response.data || []
        } else {
          this.activityTypeOptions = []
          this.$modal.msgError(response.msg || '获取活动类型列表失败')
        }
      }).catch(() => {
        this.activityTypeOptions = []
        this.$modal.msgError('获取活动类型列表失败')
      })
    },
    /** 根据活动类型ID获取名称 */
    getActivityTypeName(categoryId) {
      if (!categoryId || !this.activityTypeOptions.length) {
        return '-'
      }
      const option = this.activityTypeOptions.find(item => item.value === categoryId)
      return option ? option.label : categoryId
    },
    /** 获取活动状态文本 */
    getActivityStatusText(status) {
      const statusMap = {
        0: '未开始',
        1: '进行中',
        2: '已停用'
      }
      return statusMap[status] || '未知'
    },
    /** 获取活动状态颜色 */
    getActivityStatusType(status) {
      const typeMap = {
        0: 'info',
        1: 'success',
        2: 'danger'
      }
      return typeMap[status] || 'info'
    },
    /** 获取审核状态文本 */
    getAuditStatusText(status) {
      const statusMap = {
        0: '未提交',
        1: '待审核',
        2: '通过',
        3: '驳回'
      }
      return statusMap[status] || '未知'
    },
    /** 获取审核状态颜色 */
    getAuditStatusType(status) {
      const typeMap = {
        0: 'info',
        1: 'warning',
        2: 'success',
        3: 'danger'
      }
      return typeMap[status] || 'info'
    },
    /** 审核通过 */
    handleAuditApprove(row) {
      this.$modal.confirm('是否确认审核通过编号为"' + row.id + '"的活动申请？').then(() => {
        return this.updateAuditStatus(row.id, 2) // 审核状态改为通过
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('审核通过成功')
      }).catch(() => {})
    },
    /** 审核驳回 */
    handleAuditReject(row) {
      this.$prompt('请输入驳回原因', '审核驳回', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (value) => {
          if (!value || value.trim() === '') {
            return '请输入驳回原因'
          }
          return true
        }
      }).then(({ value }) => {
        return this.updateAuditStatus(row.id, 3, value.trim()) // 审核状态改为驳回
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('审核驳回成功')
      }).catch(() => {})
    },
    /** 更新审核状态 */
    updateAuditStatus(id, auditStatus, rejectReason = null) {
      const data = {
        id: id,
        auditStatus: auditStatus
      }
      if (rejectReason) {
        data.rejectReason = rejectReason
      }
      return auditActivity(data)
    }
  }
}
</script>
